package com.company.cloud.mall.modules.app.controller;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.mall.constant.ShopConstant.PayConfirmWay;
import com.company.cloud.mall.modules.app.controller.req.PayResultReportParam;
import com.company.cloud.mall.modules.app.service.ShopOrderPayService;
import com.company.cloud.pay.constant.ThirdPayConfirmWayEnum;
import com.company.cloud.pay.modules.alipay.AliPayApi;
import com.company.cloud.pay.modules.alipay.AliPayCore;
import com.company.cloud.pay.modules.alipay.enums.SignType;
import com.company.cloud.pay.modules.api.constant.PayStateEnum;
import com.company.cloud.pay.modules.bus.producer.PayProducer;
import com.company.cloud.pay.modules.cache.model.PayChannelConfigModel;
import com.company.cloud.pay.modules.cache.service.PayCacheService;
import com.company.cloud.pay.modules.pay.service.PaymentOrderService;
import com.company.cloud.pay.modules.third.models.ThirdPayNotifyResp;
import com.company.cloud.pay.modules.third.utils.WxPayStateConvertKit;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import io.swagger.annotations.Api;
import lombok.extern.log4j.Log4j2;

@Log4j2
@Controller
@RequestMapping("/pay")
@Api(tags = "PAY_支付宝通知服务")
public class AliPyaNotifyController {


    @Autowired
    private PayCacheService payCacheService;
    @Autowired
    private PayProducer payProducerUtils;
    @Autowired
    private PaymentOrderService paymentOrderService;
    @Autowired
    private ShopOrderPayService shopOrderPayService;

    private PayChannelConfigModel getPayChannelConfig(HttpServletRequest request) {
        try {
            // String path=request.getRequestURI();
            String path = request.getServletPath();
            String[] strs = path.split("/");
            String payConfigId = strs[strs.length - 2];
            PayChannelConfigModel payConfig = payCacheService.getPayChannelConfigByCache(Integer.parseInt(payConfigId));
            return payConfig;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 支付异步通知
     */
    @RequestMapping(value = "/alipay/{payConfigId}/payNotify", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String payNotify(HttpServletRequest request) {
        System.out.println("======支付宝回调==========");

        PayChannelConfigModel payConfig = this.getPayChannelConfig(request);
        if (payConfig == null) {
            return "参数格式校验错误";
        }

        Map<String, String> params = AliPayApi.toMap(request);
//		Map<String, String> m2= AliPayCore.paraFilter(map);
//		String sign= AliPayCore.buildRequestMySign(m2, payConfig.getPayChannelParam().getAliPrivateKey(), SignType.MD5.getType());
//		System.out.println("签名 : "+sign);

        System.out.println("--------------------------");
        if (params != null) {
            params.forEach((k, v) -> {
                System.out.println(StrUtil.format("{}={}", k, v));
            });
        }

        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, payConfig.getPayChannelParam().getAlipayPublicKey(), params.get("charset"), params.get("sign_type"));
            System.out.println("支付验签结果:" + flag);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        // 更新支付订单信息
        this.processPayNotify(payConfig, params);
        // 发送通知
        return "success";
    }


    private void processPayNotify(PayChannelConfigModel payConfig, Map<String, String> params) {
//		ThirdPayNotifyResp resp=new ThirdPayNotifyResp();
//		resp.setMchId(params.get("mch_id"));
//		resp.setAppId(params.get("appid"));
//		resp.setTotalFee(params.get("total_fee"));
//		resp.setResultCode(params.get("result_code"));
//		resp.setIsSubscribe(params.get("is_subscribe"));
//		resp.setOpenid(params.get("openid"));
//		resp.setTransactionId(params.get("transaction_id"));
//		resp.setOutTradeNo(params.get("out_trade_no"));
//		resp.setAttach(params.get("attach"));
//		resp.setTradeType(params.get("trade_type"));
//		resp.setTimeEnd(params.get("time_end"));
//		resp.setState(WxPayStateConvertKit.convertPayStateStr(resp.getResultCode()));
//		paymentOrderService.notifyCallBack(ThirdPayConfirmWayEnum.ThirdCallback_Confirm,payConfig.getServiceCode(),payConfig.getCompanyNo(),resp);
//		

        String outTradeNo = params.get("out_trade_no");
        String thirdState = params.get("trade_status");
        PayStateEnum state = WxPayStateConvertKit.convertAliPayState(thirdState);

        System.out.println("+++++++++支付结果消费++++++++++");
        PayResultReportParam bizParams = new PayResultReportParam();
        bizParams.setSn(outTradeNo);
        bizParams.setState(state.getCode());
        bizParams.setMemo("第三方支付回调");
        bizParams.setThirdState(thirdState);

        LoginSimpleUserInfo userInfo = new LoginSimpleUserInfo();
        userInfo.setId(-1);
        userInfo.setIp("127.0.0.1");

        shopOrderPayService.payReport(bizParams, PayConfirmWay.ThirdCallback_Confirm, userInfo);

    }

}
